<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link rel="stylesheet" href="SignPage.css">
</head>

<body>
    <img src="./background.jpeg"  alt="" width="2000" height="1500" class="img">
    <img src="../StaticImages/logo.png" alt="" width="192" height="120" class="Whu">
    <form class="login-form" onsubmit="login(event);">
        <label for="username">用户名:</label><br>
        <input type="text" id="username" name="username" placeholder="请输入学号" required><br>
        <label for="password">密码:</label><br>
        <input type="password" id="password" name="password" placeholder="请输入密码" required><br><br>
        <input type="submit" value="登录">
    </form>

    <script>
        async function login(event) {
            event.preventDefault();
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            if (isNaN(Number(username)) || username.trim() === "") {
                alert("账号只能为数字且不能为空");
                return false;
            }

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({ username: username, password: password }).toString(),
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.statusText);
                }

                const data = await response.json();
                if (data.token) {
                    localStorage.setItem('authToken', data.token);
                    console.log('Token saved:', data.token);
                    // 在这里可以添加跳转到首页或其他页面的逻辑  
                    window.location.href = '/'; 
                    console.log("执行跳转");
                    return false; // 阻止表单默认提交行为  
                } else {
                    throw new Error('No token received from server');
                }
            } catch (error) {
                console.error('Error during login:', error);
                alert('用户名或密码错误，请重试！');
                return false;
            }
        }

        async function fetchWithToken(url, options = {}) {
            const token = localStorage.getItem('authToken');
            if (!token) {
                throw new Error('No token found in localStorage');
            }

            const headers = {
                ...options.headers,
                'Authorization': `Bearer ${token}`,
            };

            return fetch(url, {
                ...options,
                headers,
            });
        }

        // 使用示例（在实际应用中可能不会直接放在这里）  
        fetchWithToken('/login')
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error fetching protected resource:', error));  
    </script>
</body>

</html>